package com.grq.mis.tool;


import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.gen.SourceBuilder;
import org.beetl.sql.gen.SourceConfig;
import org.beetl.sql.gen.simple.EntitySourceBuilder;
import org.beetl.sql.gen.simple.MDSourceBuilder;
import org.beetl.sql.gen.simple.MapperSourceBuilder;
import org.beetl.sql.gen.simple.SimpleMavenProject;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

public class EntityGenerateTool {

    public static void main(String[] args) throws Exception {

        // 1.初始化sqlmanager
        SQLManager sqlManager = init();
        // 2.定义要生成的表名
        String tableName = "t_order";
        // 3.生成实体类
        genConCode(sqlManager,tableName);
    }

    /**
     * 根据表名生成代码
     * @param tableName
     */
    public static void genConCode(SQLManager sqlManager,String tableName){
        SourceConfig config = new SourceConfig(sqlManager,true);

        // 自动生成选项
        List<SourceBuilder> sourceBuilder = new ArrayList<>();
        SourceBuilder entityBuilder = new EntitySourceBuilder();
        SourceBuilder mapperBuilder = new  MapperSourceBuilder();
        SourceBuilder mdBuilder = new MDSourceBuilder();

        // 实体类
        sourceBuilder.add(entityBuilder);
        // dao层
        sourceBuilder.add(mapperBuilder);
        // md文件
        sourceBuilder.add(mdBuilder);

        config.setSourceBuilder(sourceBuilder);

        // 输出到控制台
        //ConsoleOnlyProject project = new ConsoleOnlyProject();
        //config.gen(tableName,project);

        // 输出到工程
        SimpleMavenProject sp = new SimpleMavenProject();
        sp.setBasePackage("com.fht.mis");
        sp.setRoot("common");
        config.gen(tableName,sp);
    }

    /**
     * 加载sqlmanager
     * @return
     */
    public static SQLManager init() {
        DataSource dataSource = datasource();
        ConnectionSource source = ConnectionSourceHelper.getSingle(dataSource);
        SQLManagerBuilder builder = new SQLManagerBuilder(source);
        builder.setNc(new UnderlinedNameConversion());
        builder.setInters(new Interceptor[]{new DebugInterceptor()});
        builder.setDbStyle(new MySqlStyle());
        SQLManager sqlManager = builder.build();
        return sqlManager;

    }

    /**
     * 获取数据源
     * @return
     */
    public static DataSource datasource() {
        HikariDataSource dataSourceConfig = new HikariDataSource();
        dataSourceConfig.setJdbcUrl("jdbc:mysql://192.168.1.79:3306/grq_mis?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("fenghuotai");
        dataSourceConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return dataSourceConfig;
    }

}
